<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 搜索栏区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="querInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" plain @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="手机号"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="create_time" label="时间"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="ChangeState(scope.row)"></el-switch>
          </template >
        </el-table-column>
        <el-table-column label="操作" width="175px" > 
         <template slot-scope="scope">
           <!-- 修改按钮 -->
           <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEdit(scope.row.id)" ></el-button>
           <!-- 删除按钮 -->
           <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByid(scope.row.id)"></el-button>
           <!-- 分配权限按钮 -->
           <el-tooltip content="分配角色" placement="top" :enterable="false">
             <el-button type="warning" icon="el-icon-setting" size="mini" @click="rolesDirlog(scope.row)"></el-button>
           </el-tooltip>
         </template >
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="querInfo.pagenum"
      :page-sizes="[2, 5,10,15]" 
      :page-size="querInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalpage">
    </el-pagination>
    </el-card>
    <!-- 添加用户弹框 -->
    <el-dialog
     title="添加用户"
     :visible.sync="dialogVisible"
     width="50%"
     @close="closeDialogVisible"
     >
     <!-- 添加用户内容 --------------->
     <el-form :model="addRuleForm" :rules="addRules" ref="addRuleFormRef" label-width="70px">
     <el-form-item label="姓名:" prop="username">
     <el-input v-model="addRuleForm.username"></el-input>
     </el-form-item>
     <el-form-item label="密码:" prop="password">
     <el-input v-model="addRuleForm.password"></el-input>
     </el-form-item>
     <el-form-item label="email:" prop="email">
     <el-input v-model="addRuleForm.email"></el-input>
     </el-form-item>
     <el-form-item label="手机号:" prop="mobile">
     <el-input v-model="addRuleForm.mobile"></el-input>
     </el-form-item>
     </el-form>
     <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUser">确 定</el-button>
   </span>
    </el-dialog>
    <!-- 修改编辑用户对话框 ------------->
    <el-dialog
     title="修改用户信息"
     :visible.sync="editDialogVisible"
     width="50%"
     @close="restForm">
     <!-- 内容部分 -->
     <el-form :model="eidtRuleForm" :rules="eidtRules" ref="eidtRuleFormRef" label-width="70px">
     <el-form-item label="姓名:" >
     <el-input v-model="eidtRuleForm.username" disabled></el-input>
     </el-form-item>
     <el-form-item label="邮箱:" prop="email">
     <el-input v-model="eidtRuleForm.email"></el-input>
     </el-form-item>
     <el-form-item label="手机号:" prop="mobile">
     <el-input v-model="eidtRuleForm.mobile"></el-input>
     </el-form-item>
     </el-form>
    <!-- 修改用户确认取消 --页脚-->
     <span slot="footer" class="dialog-footer">
       <el-button @click="editDialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="editDialogInfor">确 定</el-button>
     </span>
   </el-dialog>
   <!-- 修改角色的弹框~~~~~~~~~~~~· -->
  <el-dialog
  title="分配角色"
  :visible.sync="rolsDialogVisible"
  width="50%"
  @close="setRoleDilogClosed">
  <div>
    <p>当前的用户：{{userinfor.username}}</p>
    <p>当前的角色：{{userinfor.role_name}}</p>
    <p>分配新角色：
     <el-select v-model="selectRloes" placeholder="请选择">
     <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
     </el-option>
     </el-select>
    </p>
  </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="rolsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="rolsDialogVisibleFal">确 定</el-button>
  </span>
</el-dialog>

  </div>
</template>
<script>
export default {
  data() { 
    // 邮箱验证规则------
    var checkEmail=(rule,value,cb)=>{
    // 验证邮箱的正则表达式
    const regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
    if(regEmail.test(value)){
        //合法的邮箱
        return cb();
    }
    cb(new Error('请输入合法的邮箱'));
    }
    //手机号验证规则------
    var checkMobile =(rule,value,cb)=>{
        const regMobile= /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
        if(regMobile.test(value)){
            return cb()
        }
        cb(new Error('请输入合法的手机号'))
    }

    return {
      // 获取列表参数
      querInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        //当前页面显示条数
        pagesize:5,
      },
      // 列表数据
      userList: [],
      // 页码总记录数
      totalpage: 0,
      //添加用户弹框是否隐藏
      dialogVisible:false,
      //添加用户表单数据
      addRuleForm:{
          username:"",
          password:"",
          email:"",
          mobile:""
      },
      //修改(查询)用户表单数据
      eidtRuleForm:{},
      //修改用户弹框是否隐藏
      editDialogVisible:false,
      // 控制角色分配弹框的显示与隐藏
      rolsDialogVisible:false,
      //需要分配角色的用户信息
      userinfor:{},
      // 获取到的所有权限数据
      rolesList:[],
      // 下拉菜单已选中的角色id值
      selectRloes:'',
      //修改表单规则的验证对象
      eidtRules:{
          //如果想用之前的，可以绑定一个ref
           email:[
              { required: true, message: '请输入邮箱', trigger: 'blur' },
              {validator:checkEmail,trigger:'blur'}
          ],
           mobile:[
            //   { required: true, message: '请输入手机', trigger: 'blur' },
            //   {validator:checkMobile,trigger:'blur'}
            // 验证规则中间带*号
             { required: true,
               type:"string",
               trigger: 'blur',
               message: '请输入正确的手机号',
               pattern:/^1[3456789][0-9]([0-9]|\*){4}\d{4}$/}
          ]
      },
      //表单数据验证对象
      addRules:{
          username:[
              { required: true, message: '请输入用户名', trigger: 'blur' },
              { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
              { required: true, message: '请输入用户密码', trigger: 'blur' },
              { min: 6, max: 8, message: '长度在 6到 8 个字符', trigger: 'blur' }
          ],
          email:[
              { required: true, message: '请输入邮箱', trigger: 'blur' },
              {validator:checkEmail,trigger:'blur'}
          ],
           mobile:[
            //   { required: true, message: '请输入手机', trigger: 'blur' },
            //   {validator:checkMobile,trigger:'blur'}
            // 验证规则中间带*号
             { required: true,
               type:"string",
               trigger: 'blur',
               message: '请输入正确的手机号',
               pattern:/^1[3456789][0-9]([0-9]|\*){4}\d{4}$/}
          ]
          },   
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
      //获取列表参数
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.querInfo,
      });
      if (res.meta.status !== 200) {
        console.log("获取列表失败！");
      } else {
        this.userList = res.data.users;
        this.totalpage = res.data.total;
      }
    },
    // 监听pagsize改变的事件
    handleSizeChange(newSize){
        // console.log(newSize)
        this.querInfo.pagesize=newSize;
        this.getUserList();
    },
    // 监听页码值事件 最新页码值
    handleCurrentChange(newPage){
        // console.log(newPage)
        this.querInfo.pagenum=newPage;
        this.getUserList();
    },
    // 监听状态是否开关
    async ChangeState(userinfor){
      // console.log(userinfor)
      const {data:res}=await this.$http.put(`users/${userinfor.id}/state/${userinfor.mg_state}`);
      if(res.meta.status!==200){
          this.$message.error('更新用户状态失败');
      }else{
          this.$message.success('更新用户状态成功');
      }
    },
    //关闭重置表单事件
    closeDialogVisible(){
        this.$refs.addRuleFormRef.resetFields();
    },
    //表单确定验证事件-----点击按钮，添加新用户
    addUser(){
        this.$refs.addRuleFormRef.validate(async valid=>{
            if(!valid) return
            // 可以发起接口请求
         const {data:res}= await this.$http.post("users",this.addRuleForm);
         if(res.meta.status!==201){
             this.$message.error('添加用户失败!')
         }else{
             this.$message.success('添加用户成功!')
             //添加成功后隐藏对话框
             this.dialogVisible=false;
             //添加成功后需重新刷新列表，再次调用接口
             this.getUserList();
         }
        })
    },
    //修改编辑用户对话框
   async showEdit(id){
       const{data:res}=await this.$http.get("users/"+id);
       if(res.meta.status!==200){
           return this.$message.error("查询用户失败!")
           }
        this.eidtRuleForm=res.data;//不太理解
        //让这个弹框显示
        this.editDialogVisible=true;
    },
    //修改表单关闭的重置事件
    restForm(){
        this.$refs.eidtRuleFormRef.resetFields();
    },
    //修改用户消息并提交
    editDialogInfor(){
      this.$refs.eidtRuleFormRef.validate(async valid=>{
          if(!valid) return
          //发起修改用户信息的数据请求
          const {data:res}= await this.$http.put("users/"+this.eidtRuleForm.id,{
               email:this.eidtRuleForm.email,
               mobile:this.eidtRuleForm.mobile, 
          })
            if(res.meta.status!==200){
              return this.$message.error("更新用户信息失败!")
           }
              //关闭对话框，
              this.editDialogVisible=false;
              // ，刷新列表
              this.getUserList();
              // 显示提示消息
              this.$message.success("更新用户信息成功！")
      })
    },
    //删除用户的方法
   async removeUserByid(id){
     //删除用户的方法
     const confirmReslut= await  this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
        ).catch(err=>err)
        // 如果用户确认删除，则返回值为字符串为confirm
        // 如果用户取消了删除，则返回值为字符串为cancel
        if(confirmReslut!=="confirm"){
          return this.$message.info('已取消删除')
        }
       const {data:res} =await this.$http.delete("users/"+id);
         if(res.meta.status!==200){
          return this.$message.error("删除用户失败！")
       }
         this.$message.success("删除用户成功！")
         this.getUserList();
       },
      // 分配角色弹框
      async rolesDirlog(userinfor){
        this.userinfor=userinfor;
        const {data:res} =await this.$http.get("roles");
        if(res.meta.status!==200){
          return this.$message.error("分配角色失败！")
        }
        this.rolesList=res.data;

        // 控制分配角色显示
        this.rolsDialogVisible=true;
       
       },
       //点击按钮，分配角色~~~~~~~~~~~NO~~~~~~~~~~~
       async rolsDialogVisibleFal(){
         if(!this.selectRloes){
           return this.$message.error('请选择要分配的角色！');
         }
         const {data:res}=await this.$http.put(`users/${this.userinfor.id}/role`,{
             rid:this.selectRloes
         })
          if(res.meta.status!==200){
            return this.$message.error('更新角色失败！')
          }
          this.$message.success('更新角色成功！')
          this.getUserList();
          this.rolsDialogVisible=false;
       },
      //分配角色关闭清空事件
      setRoleDilogClosed(){
        this.selectRloes="";
        //用户信息重置为空
        this.userinfor={};
      }

  },
};
</script>

<style lang="less" scoped>
</style>